<!DOCTYPE html>
<html lang="en">





<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" type="image/png" href="/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="My Personal Website For Blog">
  <meta name="author" content="黄宇辉">
  <meta name="keywords" content="learning note,hexo blog">
  <title>MyBatis与Spring的整合 - 欢迎参观小灰灰的网站哟 ヾ(◍°∇°◍)ﾉﾞ ~</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/vs2015.min.css" />
  

  


<!-- 主题依赖的图标库，不要自行修改 -->
<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_yg9cfy8wd6.css">

<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_pjno9b9zyxs.css">

<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script  src="/js/utils.js" ></script>
</head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>ANONYMOUS</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                Home
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                Archives
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                Tags
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                About
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="view intro-2" id="background" parallax=true
         style="background: url('/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container text-center white-text fadeInUp">
            <span class="h2" id="subtitle">
              
            </span>

            
              
  <div class="mt-3 post-meta">
    <i class="iconfont icon-date-fill" aria-hidden="true"></i>
    <time datetime="2019-05-22 21:23">
      May 22, 2019 pm
    </time>
  </div>


<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      1.6k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      26
       分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <div class="post-content mx-auto" id="post">
            
            <article class="markdown-body">
              <h2 id="学习笔记-Spring与MyBatis整合"><a href="#学习笔记-Spring与MyBatis整合" class="headerlink" title="学习笔记 : Spring与MyBatis整合"></a>学习笔记 : Spring与MyBatis整合</h2><h3 id="传统DAO方式的开发整合"><a href="#传统DAO方式的开发整合" class="headerlink" title="传统DAO方式的开发整合"></a>传统DAO方式的开发整合</h3><p><em>简介 : 采用传统DAO开发方式进行MyBatis与Spring框架的整合时,需要编写DAO接口以及接口的实现类,<code>并且需要向DAO实现类中注入SqlSessionFactory</code>,然后通过SqlSessionFactory创建SqlSession. 下面通过一个使用客户id查询数据表中客户信息的案例来演示该开发方式.</em></p>
<ol>
<li><p><em>customer.sql : 客户信息表</em></p>
<div class="hljs"><pre><code class="hljs sql"><span class="hljs-comment"># 客户信息表</span>
<span class="hljs-keyword">create</span> <span class="hljs-keyword">table</span> t_customer (

	<span class="hljs-keyword">id</span> <span class="hljs-built_in">INT</span>(<span class="hljs-number">20</span>) PRIMARY <span class="hljs-keyword">KEY</span> AUTO_INCREMENT,
	<span class="hljs-keyword">name</span> <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">10</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
	job <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">10</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
	phone <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">12</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>
	
)</code></pre></div>
</li>
<li><p><em>db.properties : 数据库配置文件</em></p>
<div class="hljs"><pre><code class="hljs t">#
#database configuration information
#
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql:xxxxxx?useSSL=false&amp;serverTimezone=UTC&amp;allowPublicKeyRetrieval=true
jdbc.username=xxxxxx
jdbc.password=xxxxxx
#
#DBCP configuration
#
jdbc.maxTotal=30    #最大连接数
jdbc.maxIdle=10     #最大空闲连接数
jdbc.initialSize=5  #初始化连接数</code></pre></div>
</li>
<li><p><em>applicationContext.xml : Spring核心配置文件</em></p>
<div class="hljs"><pre><code class="hljs xml"><span class="hljs-meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">beans</span> <span class="hljs-attr">xmlns</span>=<span class="hljs-string">"http://www.springframework.org/schema/beans"</span>
	<span class="hljs-attr">xmlns:xsi</span>=<span class="hljs-string">"http://www.w3.org/2001/XMLSchema-instance"</span>
	<span class="hljs-attr">xmlns:aop</span>=<span class="hljs-string">"http://www.springframework.org/schema/aop"</span>
	<span class="hljs-attr">xmlns:tx</span>=<span class="hljs-string">"http://www.springframework.org/schema/tx"</span>
	<span class="hljs-attr">xmlns:context</span>=<span class="hljs-string">"http://www.springframework.org/schema/context"</span>
	<span class="hljs-attr">xsi:schemaLocation</span>=<span class="hljs-string">"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"</span>&gt;</span>

	<span class="hljs-comment">&lt;!-- 读取db.properties --&gt;</span>
	<span class="hljs-tag">&lt;<span class="hljs-name">context:property-placeholder</span> <span class="hljs-attr">location</span>=<span class="hljs-string">"classpath:db.properties"</span>/&gt;</span>
	<span class="hljs-comment">&lt;!-- 配置数据源 --&gt;</span>
	<span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"dataSource"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"org.apache.commons.dbcp2.BasicDataSource"</span>&gt;</span>
		<span class="hljs-comment">&lt;!-- 数据库驱动 --&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"driverClassName"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"$&#123;jdbc.driver&#125;"</span>/&gt;</span>
		<span class="hljs-comment">&lt;!-- 连接数据库的url --&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"url"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"$&#123;jdbc.url&#125;"</span>/&gt;</span>
		<span class="hljs-comment">&lt;!-- 连接数据库的用户名 --&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"username"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"$&#123;jdbc.username&#125;"</span>/&gt;</span>
		<span class="hljs-comment">&lt;!-- 连接数据库的密码 --&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"$&#123;jdbc.password&#125;"</span>/&gt;</span>
		<span class="hljs-comment">&lt;!-- 最大连接数 --&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"maxTotal"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"$&#123;jdbc.maxTotal&#125;"</span>/&gt;</span>
		<span class="hljs-comment">&lt;!-- 最大空闲数 --&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"maxIdle"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"$&#123;jdbc.maxIdle&#125;"</span>/&gt;</span>
		<span class="hljs-comment">&lt;!-- 初始化连接数 --&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"initialSize"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"$&#123;jdbc.initialSize&#125;"</span>/&gt;</span>
	<span class="hljs-tag">&lt;/<span class="hljs-name">bean</span>&gt;</span>
	
	<span class="hljs-comment">&lt;!-- 事务管理器,依赖于数据源 --&gt;</span>
	<span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"transactionManager"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"org.springframework.jdbc.datasource.DataSourceTransactionManager"</span>&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"dataSource"</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">"dataSource"</span>/&gt;</span>
	<span class="hljs-tag">&lt;/<span class="hljs-name">bean</span>&gt;</span>
	
	<span class="hljs-comment">&lt;!-- 开启事务注解 --&gt;</span>
	<span class="hljs-tag">&lt;<span class="hljs-name">tx:annotation-driven</span> <span class="hljs-attr">transaction-manager</span>=<span class="hljs-string">"transactionManager"</span>/&gt;</span>
	
	<span class="hljs-comment">&lt;!-- 配置MyBatis工厂: 构建SqlSessionFactory --&gt;</span>
	<span class="hljs-comment">&lt;!-- 指定数据源和配置文件: 使得Spring IOC容器在初始化id为sqlSessionFactory的Bean时解析MyBatis的配置文件,并与数据源一同保存到Spring的Bean中 --&gt;</span>
	<span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"sqlSessionFactory"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"org.mybatis.spring.SqlSessionFactoryBean"</span>&gt;</span>
		<span class="hljs-comment">&lt;!-- 注入数据源 --&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"dataSource"</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">"dataSource"</span>/&gt;</span>
		<span class="hljs-comment">&lt;!-- 指定核心配置文件位置 --&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"configLocation"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"classpath:mybatis-config.xml"</span>/&gt;</span>
	<span class="hljs-tag">&lt;/<span class="hljs-name">bean</span>&gt;</span>
	
	<span class="hljs-comment">&lt;!-- 实例化Dao: 为SqlSessionDaoSupport类的子类对象注入一个SqlSessionFactory	--&gt;</span>
	<span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"customerDao"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"pers.huangyuhui.sm.dao.impl.CustomerDaoImpl"</span>&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"sqlSessionFactory"</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">"sqlSessionFactory"</span>/&gt;</span>
	<span class="hljs-tag">&lt;/<span class="hljs-name">bean</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">beans</span>&gt;</span></code></pre></div>
</li>
<li><p><em>mybatis-config.xml : MyBaits核心配置文件</em></p>
<div class="hljs"><pre><code class="hljs xml"><span class="hljs-meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span>
<span class="hljs-meta">&lt;!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">configuration</span>&gt;</span>
	<span class="hljs-comment">&lt;!-- 配置别名 --&gt;</span>
	<span class="hljs-tag">&lt;<span class="hljs-name">typeAliases</span>&gt;</span>
		<span class="hljs-comment">&lt;!-- 通过扫描包的形式定义别名: mybatis会将所有该包中的POJO类以首字母小写的非限定类名来作为它的别名 --&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">package</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"pers.huangyuhui.sm.po"</span> /&gt;</span>
	<span class="hljs-tag">&lt;/<span class="hljs-name">typeAliases</span>&gt;</span>

	<span class="hljs-comment">&lt;!-- 配置Mapper配置 --&gt;</span>
	<span class="hljs-tag">&lt;<span class="hljs-name">mappers</span>&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">mapper</span> <span class="hljs-attr">resource</span>=<span class="hljs-string">"pers/huangyuhui/sm/po/CustomerMapper.xml"</span> /&gt;</span>
	<span class="hljs-tag">&lt;/<span class="hljs-name">mappers</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">configuration</span>&gt;</span></code></pre></div>
</li>
<li><p><em>Customer.java : 持久层</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">package</span> pers.huangyuhui.sm.po;

<span class="hljs-comment">/**
 * <span class="hljs-doctag">@ClassName</span>: Customer
 * <span class="hljs-doctag">@Description</span>: 客户信息
 * <span class="hljs-doctag">@author</span>: HuangYuhui
 * <span class="hljs-doctag">@date</span>: May 24, 2019 6:38:18 PM
 *
 */</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Customer</span> </span>&#123;

	<span class="hljs-keyword">private</span> Integer id;
	<span class="hljs-keyword">private</span> String name;
	<span class="hljs-keyword">private</span> String job;
	<span class="hljs-keyword">private</span> String phone;

	<span class="hljs-function"><span class="hljs-keyword">public</span> Integer <span class="hljs-title">getId</span><span class="hljs-params">()</span> </span>&#123;
		<span class="hljs-keyword">return</span> id;
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setId</span><span class="hljs-params">(Integer id)</span> </span>&#123;
		<span class="hljs-keyword">this</span>.id = id;
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getName</span><span class="hljs-params">()</span> </span>&#123;
		<span class="hljs-keyword">return</span> name;
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setName</span><span class="hljs-params">(String name)</span> </span>&#123;
		<span class="hljs-keyword">this</span>.name = name;
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getJob</span><span class="hljs-params">()</span> </span>&#123;
		<span class="hljs-keyword">return</span> job;
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setJob</span><span class="hljs-params">(String job)</span> </span>&#123;
		<span class="hljs-keyword">this</span>.job = job;
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getPhone</span><span class="hljs-params">()</span> </span>&#123;
		<span class="hljs-keyword">return</span> phone;
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setPhone</span><span class="hljs-params">(String phone)</span> </span>&#123;
		<span class="hljs-keyword">this</span>.phone = phone;
	&#125;

	<span class="hljs-meta">@Override</span>
	<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">toString</span><span class="hljs-params">()</span> </span>&#123;
		<span class="hljs-keyword">return</span> <span class="hljs-string">"Customer [id="</span> + id + <span class="hljs-string">", name="</span> + name + <span class="hljs-string">", job="</span> + job + <span class="hljs-string">", phone="</span> + phone + <span class="hljs-string">"]"</span>;
	&#125;

&#125;</code></pre></div>
</li>
<li><p><em>CustomerMapper.xml : 映射文件</em></p>
<div class="hljs"><pre><code class="hljs xml"><span class="hljs-meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span>
<span class="hljs-meta">&lt;!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">mapper</span> <span class="hljs-attr">namespace</span>=<span class="hljs-string">"pers.huangyuhui.sm.po.CustomerMapper"</span>&gt;</span>
	<span class="hljs-comment">&lt;!-- 根据id查询客户信息,其中`customer`为Customer类的别名 --&gt;</span>
	<span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"findCustomerById"</span> <span class="hljs-attr">parameterType</span>=<span class="hljs-string">"Integer"</span>  <span class="hljs-attr">resultType</span>=<span class="hljs-string">"customer"</span>&gt;</span>
		select id,name,job,phone from t_customer where id = #&#123;id&#125;
	<span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">mapper</span>&gt;</span></code></pre></div>
</li>
<li><p><em>CustomerDao.java : DAO层</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">package</span> pers.huangyuhui.sm.dao;

<span class="hljs-keyword">import</span> pers.huangyuhui.sm.po.Customer;

<span class="hljs-comment">/**
 * <span class="hljs-doctag">@ClassName</span>: CustomerDao
 * <span class="hljs-doctag">@Description</span>: TODO
 * <span class="hljs-doctag">@author</span>: HuangYuhui
 * <span class="hljs-doctag">@date</span>: May 24, 2019 6:52:30 PM
 *
 */</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">CustomerDao</span> </span>&#123;

	<span class="hljs-comment">/**
	 * <span class="hljs-doctag">@Title</span>: findCustomerById
	 * <span class="hljs-doctag">@Description</span>: 根据id查找客户信息
	 * <span class="hljs-doctag">@param</span>: id
	 * <span class="hljs-doctag">@return</span>: Customer
	 */</span>
	<span class="hljs-function"><span class="hljs-keyword">public</span> Customer <span class="hljs-title">findCustomerById</span><span class="hljs-params">(Integer id)</span></span>;
&#125;</code></pre></div>
</li>
<li><p><em>CustomerDaoImpl.java : CustomerDao的实现类</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">package</span> pers.huangyuhui.sm.dao.impl;

<span class="hljs-keyword">import</span> org.mybatis.spring.support.SqlSessionDaoSupport;

<span class="hljs-keyword">import</span> pers.huangyuhui.sm.dao.CustomerDao;
<span class="hljs-keyword">import</span> pers.huangyuhui.sm.po.Customer;

<span class="hljs-comment">/**
 * <span class="hljs-doctag">@ClassName</span>: CustomerDaoImpl
 * <span class="hljs-doctag">@Description</span>: 实现操作客户信息接口
 * <span class="hljs-doctag">@author</span>: HuangYuhui
 * <span class="hljs-doctag">@date</span>: May 24, 2019 6:54:24 PM
 */</span>
<span class="hljs-comment">//注意:SqlSessionDaoSupport类在使用时需要一个SqlSessionFactory或一个SqlSessionTemplate对象,所以需要通过</span>
<span class="hljs-comment">//Spring给SqlSessionDaoSupport类的子类对象注入一个SqlSessionFactory或SqlSessionTemplate.这样,在子类中就</span>
<span class="hljs-comment">//能够调用SqlSessionDaoSupport类的getSqlSession()方法来获取SqlSession对象,并使用SqlSession对象中的方法!</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CustomerDaoImpl</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">SqlSessionDaoSupport</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">CustomerDao</span> </span>&#123;

	<span class="hljs-keyword">private</span> String mapperNamespace = <span class="hljs-string">"pers.huangyuhui.sm.po.CustomerMapper."</span>;

	<span class="hljs-meta">@Override</span>
	<span class="hljs-comment">// 通过id查找客户信息</span>
	<span class="hljs-function"><span class="hljs-keyword">public</span> Customer <span class="hljs-title">findCustomerById</span><span class="hljs-params">(Integer id)</span> </span>&#123;
		<span class="hljs-comment">// 调用SqlSessionDaoSupport类的getSqlSession()方法来获取SqlSession对象,并使用SqlSession对象中的方法!</span>
		<span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.getSqlSession().selectOne(mapperNamespace + <span class="hljs-string">"findCustomerById"</span>, id);
	&#125;

&#125;</code></pre></div></li>
</ol>
<p><em>在此步骤需要在Spring配置文件applicationContext.xml中编写实例化CustomerDaoImpl的配置(<code>已添加</code>),代码如下所示 :</em></p>
<div class="hljs"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"customerDao"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"pers.huangyuhui.sm.dao.impl.CustomerDaoImpl"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"sqlSessionFactory"</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">"sqlSessionFactory"</span>/&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">bean</span>&gt;</span></code></pre></div>

<ol start="9">
<li><p><em>SMTest.java : 整合测试类</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">package</span> pers.huangyuhui.sm.test;

<span class="hljs-keyword">import</span> org.junit.BeforeClass;
<span class="hljs-keyword">import</span> org.junit.Test;
<span class="hljs-keyword">import</span> org.springframework.context.ApplicationContext;
<span class="hljs-keyword">import</span> org.springframework.context.support.ClassPathXmlApplicationContext;

<span class="hljs-keyword">import</span> pers.huangyuhui.sm.dao.CustomerDao;
<span class="hljs-keyword">import</span> pers.huangyuhui.sm.po.Customer;

<span class="hljs-comment">/**
 * <span class="hljs-doctag">@ClassName</span>: SMTest
 * <span class="hljs-doctag">@Description</span>: MyBatis+Spring整合测试
 * <span class="hljs-doctag">@author</span>: HuangYuhui
 * <span class="hljs-doctag">@date</span>: May 24, 2019 7:02:26 PM
 *
 */</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SMTest</span> </span>&#123;

	<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> ApplicationContext applicationContext;

	<span class="hljs-meta">@BeforeClass</span>
	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">init</span><span class="hljs-params">()</span> </span>&#123;
		applicationContext = <span class="hljs-keyword">new</span> ClassPathXmlApplicationContext(<span class="hljs-string">"applicationContext.xml"</span>);
	&#125;

	<span class="hljs-meta">@Test</span>
	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">findCustomerByIdTest</span><span class="hljs-params">()</span> </span>&#123;
		<span class="hljs-comment">// CustomerDao customerDao = (CustomerDao) applicationContext.getBean("customerDao");</span>
		CustomerDao customerDao = (CustomerDao) applicationContext.getBean(CustomerDao<span class="hljs-class">.<span class="hljs-keyword">class</span>)</span>;

		Customer customer = customerDao.findCustomerById(<span class="hljs-number">1</span>);
		System.out.println(customer);
	&#125;
&#125;</code></pre></div>
</li>
<li><p><em>log4j.properties : 日志文件</em></p>
<div class="hljs"><pre><code class="hljs t">#Global configuration
log4j.rootLogger=DEBUG,stdout
#Log configuration
log4j.logger.pers.huangyuhui.sm.test=TRACE
#Console configuration
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.layout.ConversionPattern=%5p [%t] - %m%n</code></pre></div>
</li>
<li><p><em>程序运行结果</em></p>
<div class="hljs"><pre><code class="hljs routeros">Fetching JDBC<span class="hljs-built_in"> Connection </span><span class="hljs-keyword">from</span> DataSource
JDBC<span class="hljs-built_in"> Connection </span>[1334618867, <span class="hljs-attribute">URL</span>=xxxxxx, MySQL Connector/J] will <span class="hljs-keyword">not</span> be managed by Spring

==&gt;  Preparing: select id,name,job,phone <span class="hljs-keyword">from</span> t_customer where id = ? 
==&gt; Parameters: 1(Integer)
&lt;==      Total: 1

Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@15c25153]
Returning JDBC<span class="hljs-built_in"> Connection </span><span class="hljs-keyword">to</span> DataSource<span class="hljs-built_in">
Customer </span>[<span class="hljs-attribute">id</span>=1, <span class="hljs-attribute">name</span>=YUbuntu0109, <span class="hljs-attribute">job</span>=student, <span class="hljs-attribute">phone</span>=15111111111]</code></pre></div>



</li>
</ol>
<h3 id="Mapper接口方式的开发整合"><a href="#Mapper接口方式的开发整合" class="headerlink" title="Mapper接口方式的开发整合"></a>Mapper接口方式的开发整合</h3><p>. . .</p>

            </article>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/MyBatis/">MyBatis</a>
                    
                      <a class="hover-with-bg" href="/tags/Spring/">Spring</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" target="_blank" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <div class="post-prev col-6">
                    
                    
                      <a href="/2019/05/22/Spring-MVC%E4%B9%8B%E6%95%B0%E6%8D%AE%E7%BB%91%E5%AE%9A/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Spring MVC之数据绑定</span>
                        <span class="visible-mobile">Previous</span>
                      </a>
                    
                  </div>
                  <div class="post-next col-6">
                    
                    
                      <a href="/2019/05/22/Spring-MVC%E7%9A%84%E6%A0%B8%E5%BF%83%E7%B1%BB%E5%92%8C%E6%B3%A8%E8%A7%A3/">
                        <span class="hidden-mobile">Spring MVC的核心类和注解</span>
                        <span class="visible-mobile">Next</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </div>
                </div>
              
            </div>

            
          </div>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;TOC</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">Search</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">keyword</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  

  <footer class="mt-5">
  <div class="text-center py-3">
    <div>
      <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a>
      <i class="iconfont icon-love"></i>
      <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener">
        <span>Fluid</span></a>
    </div>
    
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


    

    
  </div>
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/js/lazyload.js" ></script>
  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/js/clipboard-use.js" ></script>



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: 'article.markdown-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 0,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "MyBatis与Spring的整合&nbsp;",
      ],
      cursorChar: "_",
      typeSpeed: 70,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    var path = "/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>







  
  
    <script>
      !function (e, t, a) {
        function r() {
          for (var e = 0; e < s.length; e++) s[e].alpha <= 0 ? (t.body.removeChild(s[e].el), s.splice(e, 1)) : (s[e].y--, s[e].scale += .004, s[e].alpha -= .013, s[e].el.style.cssText = "left:" + s[e].x + "px;top:" + s[e].y + "px;opacity:" + s[e].alpha + ";transform:scale(" + s[e].scale + "," + s[e].scale + ") rotate(45deg);background:" + s[e].color + ";z-index:99999");
          requestAnimationFrame(r)
        }

        function n() {
          var t = "function" == typeof e.onclick && e.onclick;
          e.onclick = function (e) {
            t && t(), o(e)
          }
        }

        function o(e) {
          var a = t.createElement("div");
          a.className = "heart", s.push({
            el: a,
            x: e.clientX - 5,
            y: e.clientY - 5,
            scale: 1,
            alpha: 1,
            color: c()
          }), t.body.appendChild(a)
        }

        function i(e) {
          var a = t.createElement("style");
          a.type = "text/css";
          try {
            a.appendChild(t.createTextNode(e))
          } catch (t) {
            a.styleSheet.cssText = e
          }
          t.getElementsByTagName("head")[0].appendChild(a)
        }

        function c() {
          return "rgb(" + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + ")"
        }

        var s = [];
        e.requestAnimationFrame = e.requestAnimationFrame || e.webkitRequestAnimationFrame || e.mozRequestAnimationFrame || e.oRequestAnimationFrame || e.msRequestAnimationFrame || function (e) {
          setTimeout(e, 1e3 / 60)
        }, i(".heart{width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: fixed;}.heart:after{top: -5px;}.heart:before{left: -5px;}"), n(), r()
      }(window, document);
    </script>
  














</body>
</html>
